﻿using MiniFox.Components;
using MiniFox.Infrastructure;
using MiniFox.Platform.Applications;
using MiniFox.Platform.Applications.Auth;
using MiniFox.Platform.Exceptions;
using MiniFox.Utility;
using Repository.Core.Models.Dto;
using Repository.Core.Models.Queries;
using Repository.Core.Models.VO;
using Repository.Core.Providers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Repository.Core.Services.Impls
{
    [AutoResolve]
    public class WorkSpaceService : VersioningServiceBase, IWorkSpaceService
    {
        [AutoWired]
        protected IWorkSpaceProvider Provider { get; set; }

        public WorkSpaceService(string repoName, SystemPrincipal principal) : base(repoName, principal)
        {
        }
        public ResultObject<IEnumerable<WorkItemVo>> Query(PagedQueryObject<CommonQuery> query)
        {
            var result = Provider.Query(this.RepoName, this.Identity.GlobalID, query);
            return result;
        }
        public WorkItemVo GetItem(string name)
        {
            var item = Provider.Item(this.RepoName, this.Identity.GlobalID, name);
            return item;
        }

        public WorkItemVo Create(WorkItemDto dto)
        {
            dto.OwnerID = this.Identity.GlobalID;
            dto.OwnerName = this.Identity.CombineUserName();
            if (this.Provider.Create(this.RepoName, dto))
            {
                return GetItem(dto.Name);
            }

            return null;
        }

        public WorkItemVo Update(WorkItemDto dto)
        {
            dto.OwnerID = this.Identity.GlobalID;
            dto.OwnerName = this.Identity.CombineUserName();
            if (this.Provider.Update(this.RepoName, dto))
            {
                return GetItem(dto.Name);
            }

            return null;
        }

        public void Delete(string name)
        {
            if (!Provider.Delete(this.RepoName, this.Identity.GlobalID, name))
                throw new PlatformException("ERR_OperateFail");
        }

    }
}
